<?php

class Zend_Controller_Action_Helper_Folder extends Zend_Controller_Action_Helper_Abstract
{
    private $_alfresco = array();
    private $_baseUrl = null;

    public function direct(array $alfresco)
    {
        $this->_baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();
        $this->_setAlfresco($alfresco);
        return $this;
    }

    private function _setAlfresco(array $alfresco)
    {
        $this->_alfresco['url'] = $alfresco['url'];
        $this->_alfresco['ticket'] = $alfresco['ticket'];
    }

    private function _getAlfrescoFolder()
    {
        return new Alfresco_Rest_SpacesStore($this->_alfresco['url'], $this->_alfresco['ticket']);
    }

    private function _getRoot(& $obj)
    {
        $p = array();
        foreach ($obj as $pasta)
            $p[$pasta->getTitle()] = '<li class="directory collapsed" param="root" ><a href="#" rel="ajax/getfolders/' . $pasta->getId() . '/" >' . $pasta->getTitle() . '</a></li>';

        return $this->_formatTreeView($p);
    }

    private function _formatTreeView(& $obj)
    {
        ksort($obj);

        $html = '<ul class="jqueryFileTree" style="display: none;">';
        foreach ($obj as $li)
            $html .= $li;
        $html .= '</ul>';

        return $html;
    }

    private function _hasChildrenDocument($id)
    {
        $children = $this->_getAlfrescoFolder()->getChildren($id);
        foreach ($children as $pasta) 
            if ($pasta->getType() !== 'cmis:folder') return true;
    }
    
    public function getRootFolders($id = null)
    {
        $folders = $this->_getAlfrescoFolder()->getRootFolders($id ? $id : null);

        return $this->_getRoot($folders);
    }

    public function getChildren($id)
    {
        $children = $this->_getAlfrescoFolder()->getChildren($id);
        
        if (count($children) == 0)
            die(false);

        $p = array();
        foreach ($children as $pasta) {
            if ($this->_hasChildrenDocument($pasta->getId())) {
                $p[$pasta->getTitle()] = '<li class="directory collapsed" ><a param="red" href="#!/folder/id/'.$pasta->getId().'" rel="ajax/getfolders/' . $pasta->getId() . '/" >' . $pasta->getTitle() . '</a></li>';
            }
            elseif($pasta->getType() === 'cmis:folder'){
                $p[$pasta->getTitle()] = '<li class="directory collapsed" ><a href="#" rel="ajax/getfolders/' . $pasta->getId() . '/" >' . $pasta->getTitle() . '</a></li>';
                //$p[$pasta->getTitle()] = '<li class="file ext_ppt"><a href="#" rel="ajax/getfolders/' . $pasta->getId() . '/" >' . $pasta->getTitle() . '</a></li>';
            }
        }

        return $this->_formatTreeView($p);
    }

}
